<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 朱亚杰 <zhuyajie@topthink.net>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

/**
 * 权限管理控制器
 * Class AuthManagerController
 * 
 * @author 朱亚杰 <zhuyajie@topthink.net>
 */
class AuthManagerController extends AdminbaseController {
	function _initialize() {
		parent::_initialize ();
		$this->module="Admin";
		$this->AuthGroup = D ( "AuthGroup" );
		$this->db = D ( "AuthGroup" );
		$this->group_access = D ( "AuthGroupAccess" );
		$this->AuthRule = M ( "AuthRule" );
	}
	
	/**
	 * 权限管理首页
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function index() {
		$list = $this->AuthGroup->select ();
		
		$this->assign ( '_list', $list );
		$this->assign ( '_use_tip', true );
		$this->meta_title = '权限管理';
		$this->display ();
	}
	
	/**
	 * 创建管理员用户组
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function createGroup() {
		if (IS_POST) {
			if ($this->AuthGroup->create ()) {
				if ($this->AuthGroup->add () !== false) {
					$this->success ( "添加成功！", U ( "index" ) );
				} else {
					$this->error ( "添加失败！" );
				}
			} else {
				$this->error ( $this->AuthGroup->getError () );
			}
		}
		$this->display ( '' );
	}
	
	/**
	 * 编辑管理员用户组
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function editGroup() {
		if (IS_POST) {
			$data = $this->AuthGroup->create ();
			if ($data) {
				if ($this->AuthGroup->save ( $data ) !== false) {
					$this->success ( "修改成功！", U ( 'index' ) );
				} else {
					$this->error ( "修改失败！" );
				}
			} else {
				$this->error ( $this->Role->getError () );
			}
		}
		
		$auth_group = $this->AuthGroup->find ( ( int ) $_GET ['id'] );
		
		$this->assign ( 'data', $auth_group );
		$this->display ();
	}
	
	/**
	 * 访问授权页面
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function access() {
		
	
		
		if (IS_POST) {
			
			$_POST ['rules'] = implode ( ',', $_POST [ids] );
			
			$data = $this->AuthGroup->create ();
			if ($data) {
				if ($this->AuthGroup->save ( $data ) !== false) {
					$this->success ( "修改成功！", U ( 'index' ) );
				} else {
					$this->error ( "修改失败！" );
				}
			} else {
				$this->error ( $this->Role->getError () );
			}
		} else {
			
			// 角色ID
			$group_id = intval ( I ( "get.id" ) );
			if (! $group_id) {
				$this->error ( "参数错误！" );
			}
			
			import ( "Tree" );
			$menu = new \Tree ();
			$menu->icon = array (
					'│ ',
					'├─ ',
					'└─ ' 
			);
			$menu->nbsp = '&nbsp;&nbsp;&nbsp;';
			$result = F ( 'Menu_'.$this->module );
			
			$piv_data = $this->AuthGroup->where ( array (
					"id" => $group_id 
			) )->getField ( "rules" );
			
			$piv = explode ( ',', $piv_data );
			
			$newmenus = array ();
			foreach ( $result as $m ) {
				$newmenus [$m ['id']] = $m;
			}
			
			foreach ( $result as $key => $v ) {
				$result [$key] ['level'] = $this->_get_level ( $v ['id'], $newmenus );
				$result [$key] ['parentid_node'] = ($v ['parentid']) ? ' class="child-of-node-' . $v ['parentid'] . '"' : '';
				$result [$key] ['checked'] = (in_array ( $v [id], $piv )) ? ' checked' : '';
			}
			$str = "<tr id='node-\$id' \$parentid_node>
                       <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='ids[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$title</td>
	    			</tr>";
			
			$menu->init ( $result );
			$categorys = $menu->get_tree ( 0, $str );
			
			$this->assign ( "categorys", $categorys );
			$this->assign ( "group_id", $group_id );
			$this->display ();
		}
	}
	/**
	 * 获取菜单深度
	 * 
	 * @param
	 *        	$id
	 * @param
	 *        	$array
	 * @param
	 *        	$i
	 */
	protected function _get_level($id, $array = array(), $i = 0) {
		if ($array [$id] ['parentid'] == 0 || empty ( $array [$array [$id] ['parentid']] ) || $array [$id] ['parentid'] == $id) {
			return $i;
		} else {
			$i ++;
			return $this->_get_level ( $array [$id] ['parentid'], $array, $i );
		}
	}
	/**
	 * 删除角色
	 */
	public function deleteGroup() {
		$id = intval ( I ( "get.id" ) );
		if ($id == 1) {
			$this->error ( "超级管理员角色不能被删除！" );
		}
		$count = $this->group_access ->where ( "group_id=$id" )->count ();
		if ($count) {
			$this->error ( "该角色已经有用户！" );
		} else {
			$status = $this->AuthGroup->delete ( $id );
			if ($status !== false) {
			
				
				
				$this->success ( "删除成功！", U ( 'index' ) );
			} else {
				$this->error ( "删除失败！" );
			}
		}
	}
	

	
	/**
	 * 用户组授权用户列表
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function user($group_id) {
		if (empty ( $group_id )) {
			$this->error ( '参数错误' );
		}
		
		$auth_group = M ( 'AuthGroup' )->where ( array (
				'status' => array (
						'egt',
						'0' 
				),
				'module' => 'admin',
				'type' => AuthGroupModel::TYPE_ADMIN 
		) )->getfield ( 'id,id,title,rules' );
		$prefix = C ( 'DB_PREFIX' );
		$l_table = $prefix . (AuthGroupModel::MEMBER);
		$r_table = $prefix . (AuthGroupModel::AUTH_GROUP_ACCESS);
		$model = M ()->table ( $l_table . ' m' )->join ( $r_table . ' a ON m.uid=a.uid' );
		$_REQUEST = array ();
		$list = $this->lists ( $model, array (
				'a.group_id' => $group_id,
				'm.status' => array (
						'egt',
						0 
				) 
		), 'm.uid desc', null, 'm.uid,m.nickname,m.last_login_time,m.last_login_ip,m.status' );
		int_to_string ( $list );
		$this->assign ( '_list', $list );
		$this->assign ( 'auth_group', $auth_group );
		$this->assign ( 'this_group', $auth_group [( int ) $_GET ['group_id']] );
		$this->meta_title = '成员授权';
		$this->display ();
	}
	
	/**
	 * 将分类添加到用户组的编辑页面
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function category() {
		$auth_group = M ( 'AuthGroup' )->where ( array (
				'status' => array (
						'egt',
						'0' 
				),
				'module' => 'admin',
				'type' => AuthGroupModel::TYPE_ADMIN 
		) )->getfield ( 'id,id,title,rules' );
		$group_list = D ( 'Category' )->getTree ();
		$authed_group = AuthGroupModel::getCategoryOfGroup ( I ( 'group_id' ) );
		$this->assign ( 'authed_group', implode ( ',', ( array ) $authed_group ) );
		$this->assign ( 'group_list', $group_list );
		$this->assign ( 'auth_group', $auth_group );
		$this->assign ( 'this_group', $auth_group [( int ) $_GET ['group_id']] );
		$this->meta_title = '分类授权';
		$this->display ();
	}
	public function tree($tree = null) {
		$this->assign ( 'tree', $tree );
		$this->display ( 'tree' );
	}
	
	/**
	 * 将用户添加到用户组的编辑页面
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function group() {
		$uid = I ( 'uid' );
		$auth_groups = D ( 'AuthGroup' )->getGroups ();
		$user_groups = AuthGroupModel::getUserGroup ( $uid );
		$ids = array ();
		foreach ( $user_groups as $value ) {
			$ids [] = $value ['group_id'];
		}
		$nickname = D ( 'Member' )->getNickName ( $uid );
		$this->assign ( 'nickname', $nickname );
		$this->assign ( 'auth_groups', $auth_groups );
		$this->assign ( 'user_groups', implode ( ',', $ids ) );
		$this->display ();
	}
	
	/**
	 * 将用户添加到用户组,入参uid,group_id
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function addToGroup() {
		$uid = I ( 'uid' );
		$gid = I ( 'group_id' );
		if (empty ( $uid )) {
			$this->error ( '参数有误' );
		}
		$AuthGroup = D ( 'AuthGroup' );
		if (is_numeric ( $uid )) {
			if (is_administrator ( $uid )) {
				$this->error ( '该用户为超级管理员' );
			}
			if (! M ( 'Member' )->where ( array (
					'uid' => $uid 
			) )->find ()) {
				$this->error ( '管理员用户不存在' );
			}
		}
		
		if ($gid && ! $AuthGroup->checkGroupId ( $gid )) {
			$this->error ( $AuthGroup->error );
		}
		if ($AuthGroup->addToGroup ( $uid, $gid )) {
			$this->success ( '操作成功' );
		} else {
			$this->error ( $AuthGroup->getError () );
		}
	}
	
	/**
	 * 将用户从用户组中移除 入参:uid,group_id
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function removeFromGroup() {
		$uid = I ( 'uid' );
		$gid = I ( 'group_id' );
		if ($uid == UID) {
			$this->error ( '不允许解除自身授权' );
		}
		if (empty ( $uid ) || empty ( $gid )) {
			$this->error ( '参数有误' );
		}
		$AuthGroup = D ( 'AuthGroup' );
		if (! $AuthGroup->find ( $gid )) {
			$this->error ( '用户组不存在' );
		}
		if ($AuthGroup->removeFromGroup ( $uid, $gid )) {
			$this->success ( '操作成功' );
		} else {
			$this->error ( '操作失败' );
		}
	}
	
	/**
	 * 将分类添加到用户组 入参:cid,group_id
	 * 
	 * @author 朱亚杰 <zhuyajie@topthink.net>
	 */
	public function addToCategory() {
		$cid = I ( 'cid' );
		$gid = I ( 'group_id' );
		if (empty ( $gid )) {
			$this->error ( '参数有误' );
		}
		$AuthGroup = D ( 'AuthGroup' );
		if (! $AuthGroup->find ( $gid )) {
			$this->error ( '用户组不存在' );
		}
		if ($cid && ! $AuthGroup->checkCategoryId ( $cid )) {
			$this->error ( $AuthGroup->error );
		}
		if ($AuthGroup->addToCategory ( $gid, $cid )) {
			$this->success ( '操作成功' );
		} else {
			$this->error ( '操作失败' );
		}
	}
	
	/**
	 * 将模型添加到用户组 入参:mid,group_id
	 * 
	 * @author 朱亚杰 <xcoolcc@gmail.com>
	 */
	public function addToModel() {
		$mid = I ( 'id' );
		$gid = I ( 'get.group_id' );
		if (empty ( $gid )) {
			$this->error ( '参数有误' );
		}
		$AuthGroup = D ( 'AuthGroup' );
		if (! $AuthGroup->find ( $gid )) {
			$this->error ( '用户组不存在' );
		}
		if ($mid && ! $AuthGroup->checkModelId ( $mid )) {
			$this->error ( $AuthGroup->error );
		}
		if ($AuthGroup->addToModel ( $gid, $mid )) {
			$this->success ( '操作成功' );
		} else {
			$this->error ( '操作失败' );
		}
	}
}
